package src.com.qf.controller;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.Method;

public class BaseController extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String action = request.getParameter("action");

        Class c1 = this.getClass();
        try {
            //通过方法名拿到方法对象
            Method method = c1.getMethod(action, HttpServletRequest.class, HttpServletResponse.class);
            String resultStr = (String) method.invoke(this, request, response);//方法执行后，拿到返回值

            /**
             * 视情况分类
             * 转发,重定向,json
             */
            String contextPath = request.getContextPath();
            if(resultStr.startsWith("forward")){
                String[] split = resultStr.split(":");
                request.getRequestDispatcher(split[1]).forward(request,response);
            }else if(resultStr.startsWith("redirect")){
                String[] split = resultStr.split(":");
                response.sendRedirect(contextPath + "/" + split[1]);
            }else {
                response.getWriter().print(resultStr);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }
}
